<!-- 编辑弹窗 -->
<template>
    <ele-modal
      width="520px"
      :visible="visible"
      :close-on-click-modal="true"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改分类' : '添加分类'"
      @update:visible="updateVisible"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="92px">
        <el-row :gutter="24">
          <el-col :md="24" :sm="24">
            <el-form-item label="上级分类:">
               <el-input v-model="form.parentName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :md="24" :sm="24">
            <el-form-item label="分类名称:" prop="name">
              <el-input  v-model="form.name" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :md="24" :sm="24">
            <el-form-item label="分类编号:" prop="code">
              <el-input  v-model="form.code" placeholder="请输入分类编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="form.parentId==null||form.parentId==''">
            <el-col :md="24" :sm="24">
                <el-form-item label="图标:" >
                  <el-upload action="#" ref="upload" list-type="picture-card"   :auto-upload="false" :file-list="fileList"  :class="{hide:hideUpload}" :disabled="fileList.length>=limit" :on-change="handleChange" limit="1">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}" style="width:100%;height:100%">
                      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" >
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" >
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span v-if="!removeDisable" class="el-upload-list__item-delete" @click="handleRemove(file)" >
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible" style="z-index:9999">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
              </el-col>
        </el-row>
         <el-row :gutter="24">
          <el-col :md="24" :sm="24" >
            <el-form-item label="排序索引:" >
              <el-input-number  v-model="form.orderIndex" clearable placeholder="请输入菜单索引" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :md="24" :sm="24" >
            <el-form-item label="备注:">
              <el-input v-model="form.remark" placeholder="请输入备注"  :rows="4" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
       
      </el-form>
      <div slot="footer">
        <el-button @click="updateVisible(false)">取消</el-button>
        <el-button type="primary" :loading="loading" @click="save">
          保存
        </el-button>
      </div>
    </ele-modal>
  </template>
  
  <script>
    import upload from "@/components/UpLoad/index.js";
    import { QueryAttchmentByBusinessId,GetGuid } from '@/api/attchment';
    import { AddProductCategroy,UpdateProductCategroy,QueryProductCategroyById } from '@/api/productmanager/productcategorytmanager';
  
    const DEFAULT_FORM = {
      id: '',
      name: '',
      code: '',
      remark:'',
      parentId: '',
      parentName :'',
      orderIndex : 0,
      createUser:'',
      createDate:'',
      dataSource:'',
      createUserName:'',
    };
  
    export default {
      name: 'productcategoryEdit',
      mixins: [upload],
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
      },
      data() {
        return {
          // 表单数据
          form: { ...DEFAULT_FORM },
          // 表单验证规则
          rules: {
            name: [{ required: true, message: '请输入分类名称',trigger: 'blur'}],
            code: [{ required: true,message: '请输入分类编号',trigger: 'blur'}],
            meta: [
              {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value) {
                    const error = new Error('请输入正确的JSON格式');
                    try {
                      const obj = JSON.parse(value);
                      if (typeof obj !== 'object' || obj === null) {
                        callback(error);
                        return;
                      }
                    } catch (e) {
                      callback(error);
                      return;
                    }
                  }
                  callback();
                }
              }
            ]
          },
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
        };
      },
  
      //初始化数据
      created(){
        this.limit = 1;
      },
      methods: {
       async getId(){
            let id = await GetGuid();
            this.form.id = id;
       },
         //上传图片
      handleChange(file, fileList) {
        // this.hideUpload = fileList.length >= this.limit;
        let obj = {
          orderIndex: 1, //默认值
          attType: 1, //文件类型(1:图片,2:文件)
          file: file.raw, // 文件流
          fileName: file.name, // 文件名称
          url:file.url,// 文件路径
        }
        //索引
        if(fileList!=null && fileList.length>0){
          obj.orderIndex = fileList.length;
        }
        //业务id 新增页面时，从后台获取Guid
        if(this.form){
          obj.businessId = this.form.id;  
        }
        //文件列表
        this.fileList.push(obj);
        //设置上传图片按钮是否可见
        if(this.fileList!=null && this.fileList!=undefined){
          this.hideUpload = this.fileList.length >= this.limit;
        }else{
          this.hideUpload =false;
        }
      },

        //赋值到附件
        setAttchement(id){
            QueryAttchmentByBusinessId(id).then((d)=>{
            this.fileList = [];
            d.map((item)=>{
                this.fileList.push({
                id: item.id,
                name: item.fileName,
                url: item.fileAllPath,
                businessId: item.businessId,
                orderIndex: item.orderIndex,
                });
            });
               //设置上传图片按钮是否可见
              if(this.fileList!=null && this.fileList!=undefined){
                this.hideUpload = this.fileList.length >= this.limit;
              }else{
                this.hideUpload =false;
              }
            });
        },
        /* 保存编辑 */
        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) { return false;}
            this.loading = true;
              //上传图片
          this.fileList.map((f) => {
            if (f.file != undefined) {
              f.fileType = 1;
              f.imgType = 7;
              this.uploadImg(f);
            }
          });
            const saveOrUpdate = this.isUpdate ? UpdateProductCategroy : AddProductCategroy;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },
        setData(id){
            QueryProductCategroyById(id)
            .then((res) => {
              this.$util.assignObject(this.form, {...res});
              
        });
      },
        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
        },
      },
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.form = { ...DEFAULT_FORM };
               //查询数据赋值
              this.setData(this.data.id);
              this.setAttchement(this.data.id);
              this.isUpdate = this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.isUpdate = false;
              //赋值this.form
              this.form = { ...DEFAULT_FORM };
              this.getId();
              //父节点赋值
              this.form.parentId = this.data.parentId;
              this.form.parentName = this.data.parentName;
             
            }
          } else {
            //移除校验结果并重置字段
            // this.$refs['form'].resetFields();
            //移除校验结果
            this.$refs['form'].clearValidate();
            this.form = { ...DEFAULT_FORM };
            //设置上传图片按钮是否可见
            if(this.fileList!=null && this.fileList!=undefined){
                this.hideUpload = this.fileList.length >= this.limit;
              }else{
                this.hideUpload =false;
              }
            if(this.data){
              this.form.parentId = this.data.parentId;
              this.form.parentTitle = this.data.parentTitle;
              this.isUpdate = this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            }
          }
        }
      }
    };
  </script>
  